import { reqUsers, reqUpdateUser, reqAddUser, reqDeleteUser } from './service'
import { message } from "antd";
import { Reducer, Effect } from 'umi';

export type UserManageStateType = {
  roleNames?: any,
  user?: any,
};

export type userManageModelType = {
  namespace: string;
  state: UserManageStateType;
  effects: {
    fetchUsers: Effect;
    fetchAddOrUpdateUser: Effect;
    fetchDeleteUser: Effect;
  };
  reducers: {
    save: Reducer<UserManageStateType>;
    initRoleNames: Reducer<UserManageStateType>;
  };
};

const userManageModel: userManageModelType = {
  namespace: 'userManage',
  state: {
    roleNames: {}, // 包含所有角色的对象(属性名为id值, )
    user: {}, // 当前选中的用户信息
  },
  effects: {
    // 获取用户列表
    *fetchUsers({ payload, callback }, { call, put }) {
      try {
        const { status, data: { users, roles }, msg } = yield call(reqUsers, {
          payload: {
            params: {
              ...payload
            }
          }
        })
        if (status === 0) {
          if (callback) callback(users, roles)
          yield put({
            type: 'initRoleNames',
            payload: {
              roles
            }
          })
        }else {
          message.error(msg)
        }
      }catch (e) {
        console.log(e);
      }
    },

    // 添加或修改用户
    *fetchAddOrUpdateUser({ payload, callback }, { call, select }) {
      try {
        const user = yield select((state: any) => state.userManage.user)
        const { status, msg } = yield call(user._id ? reqUpdateUser : reqAddUser, {
          payload: {
            data:{
              ...payload
            }
          }
        })
        if(status === 0) {
          message.success(`${user._id ? '修改' : '添加'}用户成功`)
          if (callback) callback()
        }else {
          message.error(msg)
        }
      }catch (e) {
        console.log(e);
      }
    },

    // 删除用户
    *fetchDeleteUser({ payload, callback }, { call }) {
      try {
        const { status, msg } = yield call(reqDeleteUser, {
          payload: {
            data:{
              ...payload
            }
          }
        })
        if (status === 0) {
          message.success('删除用户成功!')
          if (callback) callback()
        }else {
          message.success(msg)
        }
      }catch (e) {
        console.log(e)
      }
    }

  },
  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },
    initRoleNames(state = {roleNames: {}}, { payload }){
      const roleNames = payload.roles.reduce((pre: any, role: any) => {
        pre[role._id] =  role.name
        return pre
      }, {})
      return {
        ...state,
        roleNames: {
          ...state.roleNames,
          ...roleNames
        },
      }
    }
  }
}

export default userManageModel
